package com.feng.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.reggie.common.CustomException;
import com.feng.reggie.dto.SetmealDto;
import com.feng.reggie.entity.Dish;
import com.feng.reggie.entity.DishFlavor;
import com.feng.reggie.entity.Setmeal;
import com.feng.reggie.entity.SetmealDish;
import com.feng.reggie.mapper.SetmealMapper;
import com.feng.reggie.service.DishService;
import com.feng.reggie.service.SetmealDishService;
import com.feng.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐Service实现
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper,Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     * @param setmealDto
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息到套餐表setmeal中，操作setmeal表，执行insert操作
        this.save(setmealDto);

        //获得保存套餐后雪花算法生成的id
        Long setmealId = setmealDto.getId();

        //取出菜品口味
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        //遍历flavors为每一个菜品口味flavor加工上dishId
        List<SetmealDish> newSetmealDishes = setmealDishes.stream().map((setmealDish) -> {
            setmealDish.setSetmealId(setmealId);
            return setmealDish;
        }).collect(Collectors.toList());

        //保存套餐和菜品的关联信息，操作setmeal_dish表，执行insert操作
        setmealDishService.saveBatch(newSetmealDishes);
    }


    /**
     * 删除套餐，同时删除套餐和菜品的关联关系
     * @param ids
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //查询套餐状态，确定是否可以删除（在售不可删除，停售可删除）
        LambdaQueryWrapper<Setmeal> setmealQueryWrapper1 = new LambdaQueryWrapper<>();
        setmealQueryWrapper1.in(Setmeal::getId,ids);
        setmealQueryWrapper1.eq(Setmeal::getStatus,1);

        //如果不能删除，抛出一个异常
        if(this.count(setmealQueryWrapper1)>0){
            throw new CustomException("套餐正在售卖中，不能删除，请先停售。");
        }

        //如果可以删除，先删除套餐和菜品关系表中的数据
        LambdaQueryWrapper<SetmealDish> setmealDishQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(setmealDishQueryWrapper);

        //再删除套餐表中的数据
        this.removeByIds(ids);
    }
}
